<!--
  业务属性库组件
-->
<template>
  <div style="height: 100%">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :key="index" v-for="(item, index) in breadcrumbItems">{{ item }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="table-wrap-box">
      <el-container style="height: 100%">
        <el-aside class="side-wrap" width="220">
          <SideCategoryMenu :categories-tree="categoriesTree"
                            :first-default-checked="false"
                            @add-btn-click="addBtnClick"
                            @del-btn-click="delBtnClick"
                            @edit-btn-click="editBtnClick"
                            @tree-node-click="treeNodeClick"
                            @tree-node-cancel-check="treeNodeCancelCheck"/>
        </el-aside>

        <el-main class="main-wrap">
          <div style="width: 160px;display: flex;justify-content: space-around;margin-bottom: 4px">
            <el-button size="mini" @click="saveAttrBtnClick">
              <svg-icon class-name="svg-icon" icon-class="save"></svg-icon>
              保存
            </el-button>
            <el-button size="mini" icon="el-icon-plus" type="primary" @click="addAttrBtnClick">新增</el-button>
            <el-button icon="el-icon-delete" size="mini" type="danger" @click="delAttrBtnClick">删除</el-button>
          </div>
          <el-table
              :data="busiAttrData"
              :max-height="500"
              border
              fit
              row-key="id"
              size="mini"
              style="width: 100%"
              @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40">
            </el-table-column>
            <el-table-column v-for="item in columns"
                             :key="item.prop" :label="item.label"
                             :prop="item.prop"
                             align="center">
              <template slot-scope="scope">
                <span v-if="item.oper">
                  <el-button size="mini" type="text" @click="rowEditTypeClick(scope.row)">编辑</el-button>
                  <el-button size="mini" type="text" style="color: #f56c6c" @click="rowDelTypeClick">删除</el-button>
                </span>
                <template v-else>
                  <template v-if="scope.row.editState">
                    <TreeSelect v-model="busiAttrItem.basicTypeId" size="mini" v-if="item.prop === 'basicTypeLabel'"
                          :data="basicTypeData"
                          label-key="name"
                          node-key="name"
                          value-key="id"
                          :props="{label: 'text'}">
                    </TreeSelect>
                    <el-input v-else size="mini" v-model="busiAttrItem[item.prop]"></el-input>
                  </template>
                  <span v-else>
                  {{scope.row[item.prop]}}
                </span>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-main>

      </el-container>
    </el-card>
  </div>
</template>
<script>

import SideCategoryMenu from "@/components/feature/SideCategoryMenu";
import {useDialog} from "@/components/dialog/BaseDialog";
import CategoryForm from "@/components/feature/CategoryForm";
import TreeSelect from "@/components/common/TreeSelect";
import {$FeatureApi} from "@/network/feature/FeatureApi";
import {$BasicTypeApi} from "@/network/feature/BasicTypeApi";
import {$BusinessAttrApi} from "@/network/feature/BusinessAttrApi";
import '@/assets/css/featureLayout.css';
import {useFormDialog} from "@/components/formDialog/FormDialog";

export default {
  name: "BusiAttrManage",
  components: {TreeSelect, SideCategoryMenu, CategoryForm},
  data() {
    return {
      breadcrumbItems: [],
      categoriesTree: [],
      selectNode: null, // 选择的分类节点
      curKind: '',      // 当前特征种类   busi-attr
      busiAttrData: [],
      columns: [
        {prop: 'name', label: '名称', oper: false, editState: false},
        {prop: 'text', label: '显示名称', oper: false, editState: false},
        {prop: 'basicTypeLabel', label: '基类型', oper: false, editState: false},
        {prop: 'categoryName', label: '分类', oper: false, editState: false},
        {prop: 'description', label: '描述', oper: false, editState: false},
        {prop: '', label: "操作", oper: true, editState: false}
      ],
      basicTypeData: [], // 基类型数据
      busiAttrItem: {   // 新增行的数据双向绑定对象
        name: '',
        text: '',
        categoryId: '',
        categoryName: '',
        basicTypeId: '',
        description: ''
      },
      tableEditMode: false, // 单元格的是否编辑状态
      checkedIds: [],
      cateFormData: {
        id: '',
        name: '',
        parentId: '',
        parentLabel: '',
      },
    }
  },
  methods: {
    // 新增分类
    addBtnClick() {
      this.treeOper = "add";
      let parentId, parentLabel;
      if (this.selectNode) {
        parentId = this.selectNode.id;
        parentLabel = this.selectNode.name;
      }
      useFormDialog({
        title: "添加分类",
        width: "700px",
        formProps: {
          parentId,
          parentLabel
        },
      }, CategoryForm, (data) => {
        data.kind = this.curKind;
        this.handleOkClick(data);
      }, null);
    },

    // 删除分类
    delBtnClick() {
      if (!this.selectNode) {
        this.$message.info("请选择要删除的类型");
      } else {
        let msg = '确定删除选择的类型: ' + '"' + this.selectNode.label + '"';
        this.$confirm(msg, "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await $FeatureApi.deleteCategory({id: this.selectNode.id, kind: 'busiAttr'});
          if (this.$ResHandler.isOk(res)) {
            this.$message.success(res.msg);
            await this.loadCategoryTree();
          } else {
            this.$message.error(res.msg);
          }
        }).catch(err => {
          this.$message.info("取消操作");
        })
      }
    },

    // 编辑分类
    editBtnClick() {
      let name;
      if (this.selectNode) {
        name = this.selectNode.name;
      } else {
        this.$message.info("请选择要编辑的节点");
        return;
      }
      useFormDialog({
        title: "编辑分类",
        width: "700px",
        formProps: {
          name
        },
      }, CategoryForm, (data) => {
        data.id = this.selectNode.id;
        data.kind = this.curKind;
        this.handleOkClick(data);
      }, null);
    },

    // 树节点取消勾选
    treeNodeCancelCheck() {
      this.selectNode = null;
      this.loadBusiAttrData(null);
    },

    // 点击树节点
    treeNodeClick(node) {
      let {id, name, label, parentId, parentLabel} = {...node};
      this.selectNode = {id, name, label, parentId, parentLabel};
      this.loadBusiAttrData(id);
    },

    // 新增，编辑弹框点击确定
    async handleOkClick(data) {
      // let data = {...this.cateFormData};
      // data.kind = this.curKind;   // 分类的类别
      let res = null;
      if (this.treeOper === "add") {
        res = await $FeatureApi.saveCategory(data);
      } else {
        res = await $FeatureApi.updateCategory(data);
      }
      if (this.$ResHandler.isOk(res)) {
        this.$message.success(res.msg);
        await this.loadCategoryTree();
      } else {
        this.$message.error(res.msg);
      }
    },

    // 加载分类树数据
    async loadCategoryTree() {
      let res = await $FeatureApi.getCategoryTreeData({kind: this.curKind});
      this.categoriesTree = res.data;
    },

    // 保存按钮
    async saveAttrBtnClick() {
      if (!this.tableEditMode) {
        return;
      }
      let param = {...this.busiAttrItem};
      let res = null;
      if (param.id) {
        res = await  $BusinessAttrApi.update(param);
      } else {
        res = await $BusinessAttrApi.create(param);
      }
      // if (this.$ResHandler.isOk(res)) {
      //   this.$message.success(res.msg);
      // }
      this.ShowMessage(res);
      await this.loadBusiAttrData(this.selectNode.id);
      this.tableEditMode = false;
      this.busiAttrItem = {...this.busiAttrItem, name:'', text: '', basicTypeId: '', description: ''};
    },

    // 业务属性表格新增
    addAttrBtnClick() {
      if (this.tableEditMode) {
        this.$message.info("请先保存数据!");
        return;
      }
      if (!this.selectNode) {
        this.$message.info("请选择一个业务属性分类");
        return;
      }
      this.busiAttrItem.categoryName = this.selectNode.label;
      this.busiAttrItem.categoryId = this.selectNode.id;
      this.tableEditMode = true;
      let newRow = {editState: true};
      this.busiAttrData.push(newRow);
    },

    // 业务属性表格删除
    delAttrBtnClick() {
      let ids = [...this.checkedIds];
      if (!ids || ids.length === 0) {
        this.$message.error("请选择要删除的业务属性!");
        return;
      }
      this.$confirm('将删除已选择的业务属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await $BusinessAttrApi.removeByIds({ids});
        this.ShowMessage();
        await this.loadBusiAttrData(this.selectNode.id);
      }).catch(err => {
        this.$message.info("取消操作");
      })

    },

    // 表格选中项改变
    handleSelectionChange(rows) {
      this.checkedIds = rows.map(item => {
        return item.id;
      })
    },

    // 业务属性表格行编辑
    rowEditTypeClick(row) {
      if (this.tableEditMode) {
        this.$message.info("请先保存当前编辑行!");
        return;
      }
      let id = row.id;
      let tar = this.busiAttrData.find(item => item.id === id);
      if (tar) {
        this.tableEditMode = true;
        Object.assign(this.busiAttrItem, tar);
        this.$set(tar, 'editState', true);
      }
    },

    rowDelTypeClick() {

    },

    // 加载基类型数据
    async loadBasicTypeData() {
      let res = await $BasicTypeApi.getBasicTypeTreeData()
      this.basicTypeData = res.data;
    },
    // 加载业务属性表格数据
    async loadBusiAttrData(categoryId) {
      let res = await $BusinessAttrApi.list({categoryId});
      this.busiAttrData = res.data;
    }


    

  },


  watch: {
    $route: {
      handler: function (newRoute, oldRoute) {
        this.breadcrumbItems = ['特征中心', newRoute.meta.description];
        this.curKind = newRoute.meta.name;
      },
      immediate: true,
      deep: true
    }
  },

  created() {
    this.loadCategoryTree();
    this.loadBasicTypeData();
    this.loadBusiAttrData();
  }

}
</script>

<style scoped>

</style>